package com.mehdiuz.backend.role.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mehdiuz.backend.commons.utils.JwtUtils;
import com.mehdiuz.backend.commons.utils.Result;
import com.mehdiuz.backend.commons.utils.ResultCodeEnum;
import com.mehdiuz.backend.role.entity.*;
import com.mehdiuz.backend.role.entity.vo.RouterVo;
import com.mehdiuz.backend.role.entity.vo.UserVo;
import com.mehdiuz.backend.role.service.MenuService;
import com.mehdiuz.backend.role.service.RoleMenuService;
import com.mehdiuz.backend.role.service.UserRoleService;
import com.mehdiuz.backend.role.service.UserService;
import com.mehdiuz.backend.role.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 23548
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2022-10-31 19:19:06
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private AuthenticationManager manager;

    /**
     * 根据传入的用户id查询出当前用户对应的角色所拥有的菜单权限
     * @param userId
     * @return
     */
    @Override
    public Map<String,List> getRouterTree(Long userId) {
        List<UserRole> userRoles = userRoleService.getBaseMapper().selectList(new QueryWrapper<UserRole>().eq("user_id", userId));
        List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        List<RoleMenu> roleMenus = roleMenuService.findByRoleIds(roleIds);
        List<Long> menuIds = roleMenus.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        //查询出当前用户具有的所有菜单，按照routerVo进行组合
        List<Menu> menus = menuService.getBaseMapper().selectBatchIds(menuIds);
        List<Menu> buttons = new ArrayList<>(menus);
        List<RouterVo> routerVoList = menuService.assemblyRouter(menus);
        Map<String,List> map = new HashMap<>();
        map.put("menus",buttons);
        map.put("routers",routerVoList);
        return map;
    }

    /**
     * 在用户进行登录时，检查滑动验证码是否完成，security校验当前用户
     * @param user
     * @return
     */
    @Override
    public Result login(UserVo user) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = manager.authenticate(usernamePasswordAuthenticationToken);
        CustomUser customUser = (CustomUser) authenticate.getPrincipal();
        if(customUser == null){
            return Result.fail().code(ResultCodeEnum.ILLEGAL_REQUEST.getCode()).message(ResultCodeEnum.ILLEGAL_REQUEST.getMessage());
        }else {
            User selectUser = customUser.getUser();
            String uuid = user.getUuid();
            if(StringUtils.isBlank(uuid)){
                return Result.fail().code(ResultCodeEnum.ILLEGAL_REQUEST.getCode()).message(ResultCodeEnum.ILLEGAL_REQUEST.getMessage());
            }
            Jedis jedis = jedisPool.getResource();
            String check = "false";
            String jsonString = JSONObject.toJSONString(customUser);
            try {
                check = jedis.get(uuid);
                jedis.set("login"+selectUser.getUsername(),jsonString);
                jedis.expire("login"+selectUser.getUsername(),60*30);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                jedis.close();
            }
            if(check.equals("false")){
                return Result.fail().code(ResultCodeEnum.ILLEGAL_REQUEST.getCode()).message(ResultCodeEnum.ILLEGAL_REQUEST.getMessage());
            }
            if(selectUser == null){
                return Result.fail().code(ResultCodeEnum.ACCOUNT_ERROR.getCode()).message(ResultCodeEnum.ACCOUNT_ERROR.getMessage());
            }
            Map<String,String> map = new HashMap<>();
            String token = JwtUtils.createToken(selectUser.getId(), selectUser.getUsername());
            map.put("token",token);
            return Result.ok(map);
        }
    }

    @Override
    public Result logout() {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        CustomUser customUser = (CustomUser) authentication.getPrincipal();
        if(customUser==null){
            return Result.fail().code(ResultCodeEnum.SERVICE_ERROR.getCode()).message(ResultCodeEnum.SERVICE_ERROR.getMessage());
        }
        User user = customUser.getUser();
        Jedis jedis = jedisPool.getResource();
        try {
            jedis.del("login"+user.getUsername());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }
        SecurityContextHolder.clearContext();
        return Result.ok();
    }
}




